<?php
/**
 * Created by PhpStorm.
 * User: leishaofa
 * Date: 2017/7/18
 * Time: 9:41
 */

class SystemAction extends CommonAction{

    /**
     * @auth:leishaofa
     * @date:204170718
     * @parame:权限列表
    */
    public function jurisdiction(){
        $rule_model = DX('AuthRule',C('flashSale'));
        $auth = $rule_model->selectAllAuth(GROUP_NAME);
        $auth = get_column($auth);
        $this->assign('auth',$auth);
        $this->display();
    }

    /**
     * @auth:leishaofa
     * @date:204170718
     * @parame:添加权限
     */
    public function jurisdictionAdd(){
        $rule_model = DX('AuthRule',C('flashSale'));
       if(IS_POST){
          /*  if (!$rule_model->autoCheckToken($_POST)){
                // 令牌验证错误
                parent::ajaxError('表单已提交过！请关闭窗口重新填写！');
            }*/
            $data = I('post.','','trim');
            if($rule_model->isExistOpt($data['controller'], $data['action'])){
                $this->ajaxerror("该权限已存在");
            }
           $data['group']=GROUP_NAME;

            if($rule_model->addAuth($data)){
                $this->ajaxSuccess("权限添加成功");
            }else{
                $this->ajaxError("权限添加失败");
            }
        }else{
            $id = I('get.id','','intval');
            $this->assign('id',$id);
            $this->display();
        }
    }

    /**
     * @auth:leishaofa
     * @date:204170718
     * @parame:修改权限
     */
    public function jurisdictionEdit()
    {
        $rule_model = DX('AuthRule',C('flashSale'));
        if(IS_POST){
            if (!$rule_model->autoCheckToken($_POST)){
                // 令牌验证错误
                parent::ajaxError('表单已提交过！请关闭窗口重新填写！');
            }
            $data =I('post.','','trim');
            if($rule_model->isExistOpt($data['controller'], $data['action'],$data['id'])){
                $this->ajaxerror("该权限已存在");
            }
            $result = $rule_model->editAuth($data);
            if($result !== false){
                $this->ajaxSuccess('更新成功');
            }else{
                $this->ajaxError('更新失败');
            }
        }else{
            $id = is_numeric($_GET['id'])?$_GET['id']:'';
            $menu_info = $rule_model->selectAuthById($id);
            $this->assign('menu_info',$menu_info);
            $this->assign('opt',explode('/',$menu_info['act_action']));
            $this->display();
        }
    }

    /**
     * @auth:leishaofa
     * @date:204170718
     * @parame:删除权限
     */
    public function jurisdictionDelete()
    {
        $rule_model = DX('AuthRule',C('flashSale'));
        $id = I('post.id','','intval');
        if($rule_model->isExistSonAuth($id)){
            $this->ajaxError('存在子菜单不能删除');
        }
        if($rule_model->deleteAuth($id) === 1){
            $this->ajaxSuccess('删除成功');
        }else{
            $this->ajaxError('删除失败');
        }
    }

    /**
     * @auth:leishaofa
     * @date:204170718
     * @parame:角色管理
     */
    public function roleJurisdiction(){
        $auth_group_model = DX('AuthGroup',C('flashSale'));
        $page=is_numeric($_GET['p'])?$_GET['p']:'';

        $where=' ';
        if($page && IS_AJAX) {
            $startnumber=($page-1)*C('PAGENUMBER');
            $listdata = $auth_group_model->query(" select * from f_group ".$where." limit ".$startnumber.",".C('PAGENUMBER')." ");
            if (is_array($listdata) && !empty($listdata)) {
                return $this->ajaxReturn(array('code' => 101, 'msg' => "成功", 'data' => $listdata));
            } else {
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "没有数据", 'data' =>[]));
            }
            exit;
        }
        $resultcount=$auth_group_model->query('select COUNT(*) as countnum from f_group '.$where);
        $this->assign('page',ceil($resultcount[0]['countnum']/C('PAGENUMBER')));
        $this->display();
    }

   /* /**
// 编辑角色页面

    public function editGroup()
    {
        $auth_group_model = DX('AuthGroup',C('MAMI_APPDB_DB_MASTER'));
        if(IS_POST){


            if(!$params['role_name']){
                parent::ajaxError('请输入角色名称!');
            }
            $save_group_result = $auth_group_model->save($params);
            if($save_group_result === false){
                parent::ajaxError('修改失败!');
            }
            parent::ajaxSuccess('修改成功!');
        }else{
            $id = I('id', 0, 'intval');
            $group_info = $auth_group_model->findGroup($id);
            $this->assign('group_info', $group_info);
            $this->display();
        }
    }*/

    /**
     * @auth:leishaofa
     * @date:204170718
     * @efect:添加角色页面显示
     * $parame $id 修改添加标示也是自增id
     */
    public function roleAdd()
    {
        $auth_group_model = DX('AuthGroup',C('flashSale'));
        if(IS_POST){
            if (!$auth_group_model->autoCheckToken($_POST)){
                // 令牌验证错误
                parent::ajaxError('表单已提交过！请关闭窗口重新填写！');
            }
            $params = [
                'group_name' => I('title'),
                'description' => I('description'),
            ];
            if(!$params['group_name']){
                parent::ajaxError('请输入角色名称!');
            }
            if(is_numeric(trim($_POST['id']))){
                $params['group_id']=trim($_POST['id']);
                if(!$params['group_id']){
                    parent::ajaxError('角色不存在!');
                }

                $group_result = $auth_group_model->save($params);
                $title="修改";
            }else{
                $params['permissions_ids']='';
                $group_result = $auth_group_model->add($params);
                $title="添加";
            }
            if($group_result !== false) {
                parent::ajaxSuccess($title.'成功!');
            } else {
                parent::ajaxError($title.'失败!');
            }
        }else{
            $id = I('id', 0, 'intval');
            if($id) {
                $group_info = $auth_group_model->findGroup($id);
                $this->assign('group_info', $group_info);
            }
            $this->display();
        }
    }

    /**
     * @auth:leishaofa
     * @date:204170718
     * @efect:分配权限
     */
    public function ruleGroup()
    {
        $auth_group_model = DX('AuthGroup',C('flashSale'));
        $auth_rule = DX('AuthRule',C('flashSale'));
        if(IS_POST){
            if (!$auth_group_model->autoCheckToken($_POST)){
                // 令牌验证错误
                parent::ajaxError('表单已提交过！请关闭窗口重新填写！');
            }
            $data =  $_POST;
            $rule_ids = implode(",", $data['menu']);
            $role_id = $data['role_id'];
            if(!count($rule_ids)){
                $this->ajaxError('请选择需要分配的权限');
            }
            if($auth_group_model->addAuthRule($rule_ids, $role_id) == 1){
                $this->ajaxSuccess('分配成功');
            }else{
                $this->ajaxError('分配失败，请检查');
            }
        }else{
            $role_id = I('get.role_id','','intval');
            $type = I('get.type');
            if($role_id != 1){
                $info = $auth_group_model->where(['group_id' => 1])->field(['group_val'])->find();
                $a = $auth_rule->where(['act_id' => ['in',$info['group_val']]])->select();
                $menus = get_column($a, 2,0,2);
            }else{
                $menus = get_column($auth_rule->selectAllAuth(0,GROUP_NAME), 2,0,2);

            }
            $role_info = $auth_group_model->findGroup($role_id);
            if($role_info['group_val']){
                $rulesArr = explode(',',$role_info['group_val']);
                $this->assign('rulesArr',$rulesArr);
            }
            $this->assign('menus',$menus);
            $this->assign('role_id',$role_id);
            $this->assign('type',$type);
            $this->display();
        }
    }

    /**
     * @auth:leishaofa
     * @date:204170719
     * @efect:系统设置
    */
    public function setup(){
        $memberinfo=session('member_info');
        $model=M('','',C('flashSale'));
        if(IS_AJAX){
            $dao=$_POST;
            preg_match("/^$|^[^(and|or|exec|insert|select|union|update|&&|count|*|%)]*$/",trim($dao['tname']),$teamname);
            if(!$teamname[0] || strlen($teamname[0])<4){
                parent::ajaxError("团队名称包含非法字符或者太短");
            }
            $minage=is_numeric($_POST['agestarttime'])?trim($_POST['agestarttime']):18;
            $maxage=is_numeric($_POST['ageendtime'])?trim($_POST['ageendtime']):60;
            if($minage<18 || $maxage>60){
                $this->ajaxError("年龄范围不正确");
            }else if($maxage<$minage){
                $this->ajaxError("最大年龄必须大于最小年龄");
            }
            $dao['agestarttime']=date('Y-m-d',strtotime('-'.$maxage.' year'));
            $dao['ageendtime']=date('Y-m-d',strtotime('-'.$minage.' year'));
            $dao['maxuser']=is_numeric($dao['maxuser'])?$dao['maxuser']:'';
            $where = array(
                't_id'=>$memberinfo['t_id'],
            );

            $data = array(
                't_name' =>htmlspecialchars(trim($_POST['tname'])),
                'defaultpwd'=>$dao['defaultpwd'],
                'adressmaxdate'=>$dao['agestarttime'],
                'adressmindate'=>$dao['ageendtime'],
                'adresskm'=>$dao['defaultKm'],
                'addressfeatures'=>htmlspecialchars($dao['addressfeatures']),
                'defaultAccountPwd'=>$dao['defaultAccountPwd'],
            );
            $resultconfig=false;
            if(empty($memberinfo['m_type'])) {
                $config_file = CONF_PATH .'/config.php';
                $new_config = array(
                    'CopyRight' => $dao['CopyRight'],
                    'MaxPanicBuyingAccount' => $dao['MaxPanicBuyingAccount'],
                    'MaxTeamUser' => $dao['MaxTeamUser'],
                    'TeamDefaultPwd' => $dao['TeamDefaultPwd']
                );
                $resultconfig = $this->update_config($new_config,$config_file);
            }

            $resultadd= M('team','f_',C('flashSale'))->where($where)->save($data);
            if($resultadd == 1 || $resultconfig) {
                $memberinfo=array_replace($memberinfo,$data);
                session('member_info',$memberinfo);
                parent::ajaxSuccess('设置成功!');
            } else {
                parent::ajaxError('设置失败!');
            }
        }

        $query="select * from f_team where t_id=".$memberinfo['t_id'];
        $result=$model->query($query);
        $result[0]['adressmindate'] = floor((time()-strtotime($result[0]['adressmindate']))/86400/360);
        $result[0]['adressmaxdate'] = floor((time()-strtotime($result[0]['adressmaxdate']))/86400/360);
        $this->assign('memberinfo',$result[0]);
        $this->display();
    }


    /**
     * @auth:leishaofa
     * @date:204170719
     * @efect:修改密码
    */
    public function updateinfo(){
        $memberinfo=session('member_info');
        $model=M('member','f_',C('flashSale'));
        if(IS_AJAX && IS_POST){
            $dao=$_POST;
            //^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])).{6,12}
            if(!preg_match('/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z_]{8,16}$/',$dao['password'])){
                $this->ajaxError("密码6-18位字母数字组合");
            }
            if(!preg_match('/^[^(and|or|exec|insert|select|union|update|&&|count|*|%)]*$/',trim($dao['username']))){
                $this->ajaxError("用户名不正确包含特殊字符");
            }
            if(!empty(trim($dao['password']))){
                $date['m_pwd']=md5(md5(trim($dao['password'])) . C('RAND_PASSWORD'));
            }
            $date['m_name']=trim($dao['username']);

            $where=array(
                'm_id'=>$memberinfo['m_id']
            );
            $resultlinmit=$model->where($where)->save($date);
            if($resultlinmit == 1) {
                session_unset();
                cookie(null);
                parent::ajaxSuccess('修改成功!');
            } else {
                parent::ajaxError('设置失败!');
            }
        }
        $query="select m_email as eamil,m_name as username from f_member where m_id=".$memberinfo['m_id'];
        $result=$model->query($query);
        $this->assign('memberinfo',$result[0]);
        $this->display();
    }


}